package elearning.controller.admin.regist;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;
import org.slim3.datastore.Datastore;

import com.google.appengine.api.datastore.Key;

import elearning.meta.OptionMeta;
import elearning.meta.QuestionMeta;
import elearning.model.Exam;
import elearning.model.Option;
import elearning.model.Question;
import elearning.service.ElearningService;

public class InsertQuestionController extends Controller {

	private static final int OPTION_COUNT_MAX = 6;

	@SuppressWarnings("unused")
	private static final Logger logger = Logger
			.getLogger(InsertQuestionController.class.getName());

	private ElearningService service = new ElearningService();

	@Override
	public Navigation run() {
		if (!validate()) {
			return forward("addQuestion.jsp");
		}
		List<Object> models = new ArrayList<Object>();
		QuestionMeta q = new QuestionMeta();
		OptionMeta o = new OptionMeta();
		Question question = new Question();
		// exam
		Exam exam = sessionScope("exam");
		Key examKey = exam.getKey();
		Key questionKey = Datastore.allocateId(examKey, q);
		// question
		question.setKey(questionKey);
		question.setQuestion(asString("question"));
		models.add(question);
		// option
		// Iterator<Key> optionKeys = Datastore.allocateIds(questionKey, o,
		// OPTION_COUNT_MAX).iterator();
		String[] corrects = request.getParameterValues("correctArray");
		List<String> correctList = Arrays.asList(corrects);
		for (int i = 0; i < OPTION_COUNT_MAX; i++) {
			String optionName = "option" + (i + 1);
			if (requestScope(optionName) == "") {
				continue;
			}
			Key optionKey = Datastore.allocateId(questionKey, o);
			Option option = new Option();
			option.setKey(optionKey);
			option.setOption(asString("option" + (i + 1)));
			if (correctList.contains(String.valueOf(i + 1))) {
				option.setIsCorrect(true);
			} else {
				option.setIsCorrect(false);
			}
			models.add(option);
		}
		service.insertEG(models);
		return redirect("edit");
	}

	private boolean validate() {
		Validators v = new Validators(request);
		v.add("question", v.required());
		v.add("correctArray", v.required());
		if (!v.validate()) {
			return false;
		}
		String[] corrects = requestScope("correctArray");
		for (int i = 0; i < corrects.length; i++) {
			String optionName = "option" + corrects[i];
			if (requestScope(optionName) == "") {
				v.getErrors().put("option",
						"入力されていないoptionに対してcorrectを設定しています。");
				return false;
			}
		}
		return true;
	}
}
